/**
 * 
 */
package com.guohui.boot1.util.serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;

/**
 * 基于kryo的java对象序列化工具类
 * @author yanhaiqin
 * @date 2017年4月1日 上午11:50:53
 */
public class ObjectSerializer implements Serializer {

  /**
   * 序列化对象
   * @param object
   * @return
   */
  @Override
  public byte[] serialize(Object object) {
    if (object instanceof String) {
      return ((String) object).getBytes(StandardCharsets.UTF_8);
    }

    ByteArrayOutputStream byteOut = null;
    ObjectOutputStream ObjOut = null;
    try {
      byteOut = new ByteArrayOutputStream();
      ObjOut = new ObjectOutputStream(byteOut);
      ObjOut.writeObject(object);
      ObjOut.flush();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (null != ObjOut) {
          ObjOut.close();
        }
      } catch (IOException e) {
        ObjOut = null;
      }
    }
    return byteOut.toByteArray();
  }

  /**
   * 反序列化对象
   * @param buffer
   * @param clazz
   * @return
   */
  @SuppressWarnings("unchecked")
  @Override
  public <T> T deserialize(byte[] buffer, Class<T> clazz) {
    if (clazz.equals(String.class)) {
      return (T) new String(buffer);
    }

    Object rv = null;
    ByteArrayInputStream bis = null;
    ObjectInputStream is = null;
    try {
      if (buffer != null) {
        bis = new ByteArrayInputStream(buffer);
        is = new ObjectInputStream(bis);
        rv = is.readObject();
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
        bis.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return (T) rv;
  }
}
